package com.fosung.frame.modules.approve.service;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fosung.frame.common.config.Global;
import com.fosung.frame.common.service.CrudService;
import com.fosung.frame.common.utils.StringUtils;
import com.fosung.frame.modules.approve.entity.HomeApprove;
import com.fosung.frame.modules.checkinfos.entity.Checkinfos;
import com.fosung.frame.modules.checkinfos.service.CheckinfosService;
import com.fosung.frame.modules.life.entity.OrganizeLifeType;
import com.fosung.frame.modules.life.service.OrganizeLifeTypeService;
import com.fosung.frame.modules.partyassessmentinfo.dao.PartyAssessmentInfoDao;
import com.fosung.frame.modules.score.dao.PartyScoreDetailDao;
import com.fosung.frame.modules.score.dao.PersonScoreDetailDao;
import com.fosung.frame.modules.score.entity.OrganizePersonDetail;
import com.fosung.frame.modules.score.entity.PartyScoreDetail;
import com.fosung.frame.modules.score.entity.PersonScoreDetail;
import com.fosung.frame.modules.score.service.OrganizePersonDetailService;
import com.fosung.frame.modules.score.service.PartyScoreDetailService;
import com.fosung.frame.modules.sys.entity.MeetingClassification;
import com.fosung.frame.modules.sys.utils.UserUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Service
@Transactional(readOnly = true)
public class PartyScoreService extends CrudService<PartyScoreDetailDao, PartyScoreDetail> {

	@Autowired
	private PersonScoreDetailDao personScoreDetailDao;

	@Autowired
	private PartyAssessmentInfoDao partyAssessmentInfoDao;
	
	@Autowired
	private HomeApproveService homeApproveService;

	@Autowired
	private CheckinfosService checkinfosService;
	
	@Autowired
	private PartyScoreDetailService partyScoreDetailService;
	
	@Autowired
	private OrganizePersonDetailService organizePersonDetailService;

	/**
	 * 查询该党员当前年度积分项总分
	 * 
	 * @param partyScoreDetail
	 * @return
	 */
	public String isUpperPartyTotalScore(PartyScoreDetail partyScoreDetail) {
		PartyScoreDetail temp = dao.findPartyTotalScore(partyScoreDetail);
		double totalScore = temp == null ? 0 : Math.abs(Double.parseDouble(temp.getTotalScore()));
		if(!StringUtils.isEmpty(partyScoreDetail.getIsBatch()) && "1".equals(partyScoreDetail.getIsBatch())) {
			PartyScoreDetail obj = dao.findPartyNoShTotalScore(partyScoreDetail);
			double noShScore = Math.abs(Double.parseDouble(obj.getTotalScore()));
			totalScore = totalScore + noShScore;
		}
		
		double upperScore = Double.parseDouble(partyAssessmentInfoDao.get(partyScoreDetail.getPartyAssessmentInfoId()).getUpperLimitScore());
		double applyScore = Double.parseDouble(partyScoreDetail.getScore());
		String type = partyScoreDetail.getType();
		double score = 0;
		if("1".equals(type)) {
			score = totalScore + applyScore;
		}else if("2".equals(type)){
			score = Math.abs(totalScore - applyScore);
		}
		if (score > upperScore) {
			return "1";
		} else {
			return "0";
		}
	}

	/**
	 * 查询党组织积分明细
	 * 
	 * @param partyScoreDetail
	 * @return
	 */
	public List<PartyScoreDetail> findPartyScoreDetailList(PartyScoreDetail partyScoreDetail) {
		List<PartyScoreDetail> list = dao.findPartyScoreDetailList(partyScoreDetail);
		for (int i = 0; i < list.size(); i++) {
			PartyScoreDetail detail = list.get(i);
			String status = detail.getStatus();
			if("4".equals(status) || "5".equals(status) ) {
				detail.setIsUpperStatus("1");
			}else if(status == null) {
				String isUpperScoreStatus = isUpperPartyTotalScore(detail);
				detail.setIsUpperStatus(isUpperScoreStatus);
			}
		}
		return list;
	}

	/**
	 * 查询党员积分内容明细
	 * 
	 * @param personScoreDetail
	 * @return
	 */
	public List<PersonScoreDetail> findPersonScoreDetailList(PersonScoreDetail personScoreDetail) {
		List<PersonScoreDetail> list = personScoreDetailDao.findList(personScoreDetail);
		return list;
	}

	/**
	 * 查询签到党员明细
	 * 
	 * @param organizePersonDetail
	 * @return
	 */
	public List<OrganizePersonDetail> findOrganizePersonDetailList(OrganizePersonDetail organizePersonDetail) {
		List<OrganizePersonDetail> list = organizePersonDetailService.findList(organizePersonDetail);
		for (int i = 0; i < list.size(); i++) {
			OrganizePersonDetail person = list.get(i);
			String status = person.getStatus();
			if("4".equals(status) || "5".equals(status)) {
				person.setIsUpperStatus("1");
			}else if(status == null) {
				String isUpperStatus = organizePersonDetailService.isUpperPersonTotalScore(person);
				person.setIsUpperStatus(isUpperStatus);
			}
		}
		return list;
	}
	
	/**
	 * 针对党员积分审批 每个党员审核积分可以自设
	 * @param organizePersonDetail
	 * @return
	 */
	public List<OrganizePersonDetail> findOrganizePersonDetailList1(OrganizePersonDetail organizePersonDetail) {
		List<OrganizePersonDetail> list = organizePersonDetailService.findList(organizePersonDetail);
		for (int i = 0; i < list.size(); i++) {
			OrganizePersonDetail person = list.get(i);
			String status = person.getStatus();
			if("4".equals(status) || "5".equals(status)) {
				person.setIsUpperStatus("1");
			}else if(status == null) {
				String isUpperStatus = organizePersonDetailService.isUpperPersonTotalScore1(person);
				person.setIsUpperStatus(isUpperStatus);
			}
		}
		return list;
	}

	/**
	 * 活动积分审批 同意操作
	 * 
	 * @param organizeLife
	 * @return
	 */
	@Transactional(readOnly = false)
	public String agreeOrganizeLifeScore(HomeApprove homeApprove) {
		String msg = "{\"code\":\"200\",\"result\":\"审批成功\"}";
		try {
			String organizeLifeId = homeApprove.getId();
			String shState = homeApprove.getShstate();
			homeApproveService.updateApproveShState(homeApprove);
	
			// 保存审核意见
			Checkinfos checkinfos = new Checkinfos(organizeLifeId, UserUtils.getUser().getId(), shState, homeApprove.getShyj());
			checkinfosService.saveShjfyj(checkinfos);
	
			List<PartyScoreDetail> partyScoreDetailList = homeApprove.getPartyScoreDetailList();
			if(partyScoreDetailList != null) {
				for (int i = 0; i < partyScoreDetailList.size(); i++) {
					PartyScoreDetail partyScoreDetail = partyScoreDetailList.get(i);
					partyScoreDetailService.updateStatusAndScore(partyScoreDetail);
				}
			}
			
			List<OrganizePersonDetail> organizePersonDetailList = homeApprove.getOrganizePersonDetailList();
			if(organizePersonDetailList != null) {
				for(int i=0;i<organizePersonDetailList.size();i++) {
					OrganizePersonDetail organizePersonDetail = organizePersonDetailList.get(i);
					organizePersonDetailService.updateStatusAndScore(organizePersonDetail);
				}
			}
			msg = "{\"code\":\"200\",\"result\":\"审批成功\"}";
		}catch(Exception e) {
			e.printStackTrace();
			msg = "{\"code\":\"500\",\"result\":\"审批失败\"}";
		}
		return msg;
	}

	/**
	 * 退回、拒绝积分申请操作
	 * 
	 * @param partyScoreDetail
	 */
	@Transactional(readOnly = false)
	public String rejectOrganizeLifeScore(HomeApprove homeApprove) {
		String msg = "{\"code\":\"200\",\"result\":\"审批成功\"}";
		try {
			String organizeLifeId = homeApprove.getId();
			String shState = homeApprove.getShstate();
			homeApproveService.updateApproveShState(homeApprove);
	
			Checkinfos checkinfos = new Checkinfos(organizeLifeId, UserUtils.getUser().getId(), shState, homeApprove.getShyj());
			checkinfosService.saveShjfyj(checkinfos);
	
			PartyScoreDetail partyScoreDetail = new PartyScoreDetail();
			partyScoreDetail.setStatus(shState);
			partyScoreDetail.setOrganizeLifeId(organizeLifeId);
			partyScoreDetail.setCheckScore("0");
			partyScoreDetailService.updateStatusAndScore(partyScoreDetail);
			
			OrganizePersonDetail organizePersonDetail = new OrganizePersonDetail();
			organizePersonDetail.setStatus(shState);
			organizePersonDetail.setCheckScore("0");
			organizePersonDetail.setOrganizeLifeId(organizeLifeId);
			organizePersonDetailService.updateStatusAndScore(organizePersonDetail);
			
			msg = "{\"code\":\"200\",\"result\":\"审批成功\"}";
		}catch(Exception e) {
			e.printStackTrace();
			msg = "{\"code\":\"500\",\"result\":\"审批失败\"}";
		}
		return msg;
	}

	/**
	 *批量退回、拒绝党组织积分申请操作
	 * @param homeApprove
	 * @return
	 */
	@Transactional(readOnly = false)
	public String batchUpdateOrganizeLifeStatus(HomeApprove homeApprove) {
		String msg = "操作成功";
		String shState = homeApprove.getState().substring(0, 1);
		try {
			String[] ids = homeApprove.getIds().split(",");
			for(int i=0; i<ids.length; i++) {
				HomeApprove tmp = new HomeApprove();
				tmp.setId(ids[i]);
				tmp.setShstate(shState);
				rejectOrganizeLifeScore(tmp);
				Checkinfos info = new Checkinfos(ids[i],UserUtils.getUser().getId(),shState,null);
				checkinfosService.saveShjfyj(info);
			}
		}catch(Exception e) {
			e.printStackTrace();
			msg = "操作失败";
		}
		return msg;
	}


	@Autowired
	private OrganizeLifeTypeService organizeLifeTypeService;
	public static final String GMEETING_CLASSIFICATION = Global.getConfig("getMeetingClassificationList");
	
	@Transactional(readOnly = false)
	public void callMeetingClassification(String orgCode,String orgId) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			String url = GMEETING_CLASSIFICATION + orgCode;
			HttpGet httpget = new HttpGet(url);
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					organizeLifeTypeService.deleteOrganizeLifeType(orgId);
					String json = EntityUtils.toString(entity);
					Gson gson = new Gson();
					List<MeetingClassification> list = gson.fromJson(json, new TypeToken<List<MeetingClassification>>(){}.getType());
					for(int i=0; i<list.size(); i++) {
						MeetingClassification meetingClassification = list.get(i);
						OrganizeLifeType obj = new OrganizeLifeType();
						obj.setTypename(meetingClassification.getClassificationName());
						obj.setSort(meetingClassification.getSort());
						obj.setRemark(meetingClassification.getRemark());
						obj.setOrgId(orgId);
						obj.setHasChildren(meetingClassification.getHasChildren());
						obj.setClassificationId(meetingClassification.getClassificationId());
						organizeLifeTypeService.save(obj);
					}
				}
			} finally {
				response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 批量同意时，校验是否超过上限
	 * @param homeApprove
	 * @return
	 */
	public String checkScoreTotal(HomeApprove homeApprove) {
		String ids = homeApprove.getIds();
		String msg = "{\"code\":\"200\",\"lifeName\":\"\"}";
		String[] arr = ids.split(",");
		String str = "";
		for(int i=0; i<arr.length; i++) {
			str +="'" + arr[i] +"',";
		}
		str = str.substring(0, str.length()-1);
		
		for(int i=0; i<arr.length; i++) {
			String id = arr[i];
			HomeApprove home = homeApproveService.get(id);
			PartyScoreDetail party = new PartyScoreDetail();
			party.setOrganizeLifeId(id);
			List<PartyScoreDetail> partyList = dao.findList(party);
			for(int j=0; j<partyList.size(); j++) {
				PartyScoreDetail partyScoreDetail = partyList.get(j);
				partyScoreDetail.setIsBatch("1");//是否批量操作  0否 1是
				partyScoreDetail.setIds(str);
				String isTotal = isUpperPartyTotalScore(partyScoreDetail);
				if("1".equals(isTotal)) {
					return "{\"code\":\"500\",\"lifeName\":\""+home.getLifename()+"\"}";
				}
			}
			
			OrganizePersonDetail person = new OrganizePersonDetail();
			person.setOrganizeLifeId(id);
			List<OrganizePersonDetail> personList = organizePersonDetailService.findList(person);
			for(int j=0; j<personList.size(); j++) {
				OrganizePersonDetail organizePersonDetail = personList.get(j);
				organizePersonDetail.setIds(str);
				organizePersonDetail.setIsBatch("1");//是否批量操作  0否 1是
				String isTotal = organizePersonDetailService.isUpperPersonTotalScore1(organizePersonDetail);
				if("1".equals(isTotal)) {
					return "{\"code\":\"500\",\"lifeName\":\""+home.getLifename()+"\"}";
				}
			}
		}
		return msg;
	}
	
	/**
	 * 批量同意积分申请操作
	 * @param homeApprove
	 * @return
	 */
	@Transactional(readOnly = false)
	public String batchAgreeOrganizeLife(HomeApprove homeApprove) {
		String msg = "";
		try {
			String[] ids = homeApprove.getIds().split(",");
			for(int i=0; i<ids.length; i++) {
				String organizeLifeId = ids[i];
				HomeApprove tmp = new HomeApprove();
				tmp.setId(organizeLifeId);
				tmp.setShstate("3");
				homeApproveService.updateApproveShState(tmp);
				Checkinfos info = new Checkinfos(organizeLifeId,UserUtils.getUser().getId(),"3",null);
				checkinfosService.saveShjfyj(info);
				organizePersonDetailService.batchAgreePersonScoreDetail(organizeLifeId);
				partyScoreDetailService.batchAgreePartyScoreDetail(organizeLifeId);
			}
			msg = "审批成功";
		}catch(Exception e) {
			e.printStackTrace();
			msg = "审批失败";
		}
		
		return msg;
	}

}
